package com.hj.biz;

import java.util.Base64;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.hj.util.FileUtils;

/**
 * @author dehui dou
 * @date 2020/9/30 15:40
 * @description 异步任务biz,需处理异常
 */
@Service
public class AsyncTaskBiz {
    private static Logger logger = LoggerFactory.getLogger(AsyncTaskBiz.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*
     * url预览方式缓存key K->url V->viewName
     */
    String FILE_VIEW_URL = "FILE:VIEW:URL_%s";

    /**
     * @author dehui dou
     * @description url方式预览时,每次预览需要清理上次预览的转换文件,并缓存最新预览信息</br>
     *              redis存储 k->url参数 v->最新文件名称
     * @param url
     *            url预览时,传递的url参数
     * @param newFileViewName
     *            最新生成的文件预览名称
     * @return void
     */
    @Async("urlViewUpdateExecutor")
    public void updateUrlViewInfo(String url, String newFileViewName) {
        String encodedUrl = null;
        try {
            encodedUrl = Base64.getEncoder().encodeToString(url.getBytes("UTF-8"));
            String urlKey = String.format(FILE_VIEW_URL, encodedUrl);
            String value = stringRedisTemplate.opsForValue().get(urlKey);
            if (StringUtils.isNotEmpty(value)) {
                // 清理文件
                FileUtils.delFile(value);
            }
            stringRedisTemplate.opsForValue().set(urlKey, newFileViewName, 24L, TimeUnit.HOURS);
        } catch (Exception e) {
            logger.error("更新url预览文件失败", e);
        }

    }

}
